﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Missile : Weapon {

	protected Vector3 targetEndPosition;
	public bool isFast = true; //飞行速度是否是快的
	public bool isAttack = false;//子弹是否是攻击状态
	public bool isInPool = true;//是否在对象池里面

	protected List<GameObject> enemys;
	protected List<GameObject> heros;

	protected float MAX_ROTATION = 30;// 每秒最大可旋转的角度
	protected float max_rotation = 5f; // 每帧最大可旋转的角度
	public GameObject target;//攻击目标
	protected float explodeR = 1f;//爆炸半径



	// Use this for initialization
	void Start () {
		enemys = new List<GameObject>();
		heros = new List<GameObject>();
	}
	
	// Update is called once per frame
	void Update () {
		if(isAttack)
		{
			timer += Time.deltaTime;
			// 达到销毁时间
			if(timer >= durationTime)
			{
				StoreInPool();
			}
			// 丢失目标
			if(target == null && isAttack)
			{
//				print("目标丢失");
				// 未到销毁时间
				if(durationTime - timer >= 0)
				{
					// 运动
//					Debug.Log("目标死了，我还在运动");
//					MissileMove(targetEndPosition);
					MissileMoveLine(targetEndPosition);
				}
				else
				{
					StoreInPool();
				}
				return;
			}
			if(target != null)
			{
				targetEndPosition = target.transform.position;
				if (isFast) {
					MissileMove (target.transform.position);
				} else 
				{
					if (timer <= 1) 
					{
						MissileMoveLine ();
					} else 
					{
						MissileMoveLine (targetEndPosition);
					}
				}
			}
		}
	}
		

	/// <summary>
	/// This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
	/// </summary>
	void FixedUpdate()
	{

	}



	// 导弹移动
	protected void MissileMove(Vector3 targetPosition)
	{
		float dx = targetPosition.x - this.transform.position.x;
		float dy = targetPosition.y - this.transform.position.y;
		float rotationZ = Mathf.Atan2(dy, dx) * Mathf.Rad2Deg;

		//得到最终的角度并且确保在 [0, 360) 这个区间内     
        	rotationZ -= 90;
        	rotationZ = MakeSureRightRotation(rotationZ);

        	//获取增加的角度
        	float originRotationZ = MakeSureRightRotation(this.transform.eulerAngles.z);
        	// float addRotationZ = rotationZ - originRotationZ;
			float addRotationZ = MakeSureRightRotation(rotationZ - originRotationZ);

        	//超过 180 度需要修改为负方向的角度
        	if (addRotationZ > 180)
        	{	
            	addRotationZ -= 360;
        	}
			
			

        	//不超过每帧最大可旋转的阀值
        	addRotationZ = Mathf.Max(-max_rotation, Mathf.Min(max_rotation, addRotationZ));
			
			//应用旋转
        	this.transform.eulerAngles = new Vector3(0, 0, this.transform.eulerAngles.z + addRotationZ);
        	//移动
        	this.transform.Translate(new Vector3(0,speed * Time.deltaTime, 0));
		
	}


	protected float MakeSureRightRotation(float rotation)
    {
        rotation += 360;
        rotation %= 360;
        return rotation;
    }

	  
	public void SetTarget(GameObject target)
	{
	  this.target = target;
	}

	void OnTriggerEnter2D(Collider2D collision)
	{
		if(trigger)
		{
			// 子弹碰到敌人
			if(collision.tag == "Enemy")
			{
				if(!isInPool)
				{
//					print("碰到敌人");
					
					// collision.gameObject.SendMessage("TakeDamage", damage);
					StoreInPool();
					
				}
			}
		}
		else
		{
			// 子弹碰到hero
			if(collision.tag == "Hero")
			{
				if(collision.gameObject != null)
				{
					print("碰到hero");
					// collision.gameObject.SendMessage("TakeDamage", damage);
					StoreInPool();	
				}
			}
		}
	}



	public virtual void StoreInPool()
	{		
		isAttack = false;
		MissileExplode();
		transform.position = new Vector3(1000, 1000, 0);
		timer = 0;
		target = null;
		PoolControl.instance.missilePool.Store(gameObject);
		isInPool = true;
	}

	// 导弹发生爆炸
	protected void MissileExplode()
	{
		Collider2D[] colliders= Physics2D.OverlapCircleAll(transform.position, explodeR);
		// foreach (Collider2D item in colliders)
		// {
		// 	print(item.name);
		// }
		foreach (Collider2D collider in colliders)
		{
			if(collider.tag == "Enemy")
			{
				enemys.Add(collider.gameObject);
			}
			if(collider.tag == "Hero")
			{
				heros.Add(collider.gameObject);
			}
		}
		
		MadeDamage();
		ExplodeAnim();
	}

	protected void MadeDamage()
	{
		if(trigger)
		{
			// print("enemys.count--->" + enemys.Count);
			foreach (GameObject enemy in enemys)
			{
				if(enemy != null)
				{
					enemy.SendMessage("TakeDamage", damage);
				}
			}
			enemys.Clear();
		}
		else
		{
			foreach (GameObject hero in heros)
			{
				if(hero != null)
				{
					hero.SendMessage("TakeDamage", damage);
				}
			}
			heros.Clear();
		}
	}

	public void MissileMoveLine()
	{
		this.transform.Translate(new Vector3(0,speed * Time.deltaTime, 0));
	}

	public void MissileMoveLine(Vector3 targetEndPosition){
		if (target != null) {
			if (Vector3.Distance (transform.position, targetEndPosition) < 0.2f) 
			{
				target = null;
			}
			Vector3 dir = targetEndPosition - transform.position;
			this.transform.up = dir.normalized;
			this.transform.Translate (new Vector3 (0, speed * Time.deltaTime, 0));
		} else 
		{
			MissileMoveLine ();
		}

	}

	protected void ExplodeAnim()
	{

	}


}
